var rate = 0; //分辨转换
var floatTop = 0; //悬浮高度
var api = require('../../utils/api.js')
var services = require('../../config/config.js');

var app = getApp()
Page({
  data: {
    systemInfo: {},
    _api: {},
    currentCategoryId: '0',
    limit: 16,
    offset: 0,
    pageTotal: 0,
    swipers: [],
    images:[],
    categoris:[],
    hot_last_id: 0,
    latest_list: [],
    latest_last_id: 0,
    isShowFloatTab: false //是否显示悬浮tab
  },

  onLoad () {
    var that = this
    app.getSystemInfo(function(res) {
      that.setData({
        systemInfo: res
      })
    })

    that.setData({
      _api: api
    })

    this.getCategory();
    this.getDefaultList();
    this.getScrollTop();

  },

  /**
   * 点击跳转详情页
   */
  onItemClick (e) {
    var targetUrl = api.PAGE_FIGURE_DEMO
    if (e.currentTarget.dataset.rowId != null)
      targetUrl = targetUrl + '?rowId=' + e.currentTarget.dataset.rowId
    wx.navigateTo({
      url: targetUrl
    })
  },
  onClickLike (e) {
    // console.log("data: ", this.data);
    var images = this.data.images;
    images.forEach(function(i){
      // console.log("i.id=", i.id, "rowId=", e.currentTarget.dataset.rowId);
      if(i.id==e.currentTarget.dataset.rowId){
        i.favorited=!i.favorited;
      }

      // console.log("update favorited:", i.favorited);
    })
    console.log("images:", images);
    this.setData({images:images});

    var data = {uid: app.globalData.userInfo.uid, imageId: e.currentTarget.dataset.rowId};
    console.log("post data ", data);
    api.post(services.favoriteUrl+"/add", data)
    .then(function(res){
      console.log("res: ", res);
      wx.showToast({
        title: res.data.status.message,
        icon: 'none',
        duration: 600
      });
    });
  },
  /**
   * 切换 navbar
   */
  swichNav (e) {
    console.log(e.detail.id);
    var id = e.detail.id;
    if(this.data.currentCategoryId !== id)
    {
      //设置当前tab的ID以及off
      this.data.currentCategoryId = id;
      this.data.offset = 0;

      //更新categories的选中值
      for (var i = 0; i < this.data.categoris.length; i++) {
        if (id == this.data.categoris[i].id) {
          this.data.categoris[i].isSelect = true;
        } else {
          this.data.categoris[i].isSelect = false;
        }
      }
      //重新设置数据来渲染界面
      this.setData({categoris:this.data.categoris });
      if(id == 0){
        this.getDefaultList();
      }else
      {
      this.getImagesByCategoryId(id);
      }
    }
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh () {
    console.log("onPullDownRefresh - 下拉刷新");
    this.pullUpLoad();
   /*
    switch (this.data.currentNavbar) {
      case '0':
        this.setData({
          list: [],
          hot_last_id: 0
        })
        this.pullUpLoad()
        break
      case '1':
        this.setData({
          latest_list: [],
          latest_list_id: 0
        })
        this.pullUpLoadLatest()
        break
      case '2':
        wx.stopPullDownRefresh()
        break
    }*/
  },

  /**
   * [最新]上拉刷新,触发条件：当前tab为“Recommend"
   */
  pullUpLoad() {
    console.log("pullUpLoad - 上拉刷新");
    console.log("current id - "+this.data.currentCategoryId);
    if(this.data.currentCategoryId == 0)
    {
      wx.showNavigationBarLoading()
      //刷新列表
      this.getDefaultList();
    }
  },

  /**
   *获取默认数据
   */
  getDefaultList () {
    api.get(api.HOST_EASYDRAW_PRD + api.DEFAULT)
      .then(res => {
        console.log("getDefaultList", res.data);

        this.setData({
          swipers: res.data.data.bannerData.bannerList,
          images: res.data.data.imageData.imageList
        })
      })
  },

 /**
   *获取分类列表
   */
  getCategory () {
    api.get(api.HOST_EASYDRAW_PRD + api.CATEGORY)
      .then((res)=>{
        var recommendObj = {"color":"#EE6A50","name":"RECOMMEND","id":"0","isSelect":true};
        res.data.data.categoryList.unshift(recommendObj); 
    
        for(var i = 1; i < res.data.data.categoryList.length; i++){
          var obj = res.data.data.categoryList[i];
          obj['iseSelect'] = false;
        } 

        this.setData({
          categoris: res.data.data.categoryList
        })
       
        console.log(this.data.categoris);
      })
    },

    /*
      * 
      */
    onReachBottom(){
      
      //判断是否到底了
      var offset = this.data.offset + this.data.limit;
      if(offset >= this.data.pageTotal){
        wx.showToast({
          title: '对不起，没有更多数据了，让您失望了！',
          icon: 'none',
          duration: 600
        });
      }
      else
      {
        console.log("current id - "+this.data.currentCategoryId);
        if(this.data.currentCategoryId != 0)
        {
        
          console.log("The current offset is :" + offset);
          api.get(api.HOST_EASYDRAW_PRD + api.CATEGORY_IMAGES + "/"+ this.data.currentCategoryId +"/images?limit="+this.data.limit+"&offset="+offset)
            .then(res => {
              console.log(res.data);
              this.setData({
                images: this.data.images.concat(res.data.data.imageList)
              })
              wx.hideNavigationBarLoading()
              wx.stopPullDownRefresh()
            })
          this.data.offset = offset;  
        }
      }
      console.log(this.data.images);

    },

  /**
   *
   */
  getImagesByCategoryId (id) {
    api.get(api.HOST_EASYDRAW_PRD + api.CATEGORY_IMAGES + "/"+ id +"/images?limit=16&offset=0" )
      .then(res => {
        this.setData({
          images: res.data.data.imageList,
          pageTotal: res.data.data.paging.total
        })
      })
  },

  upper: function(e) {
    console.log(e)
  },
  lower: function(e) {
    console.log(e)
  },
  scroll: function(e) {
    console.log(e)
  },
  /**
   * 获得滑动导致悬浮开始的高度
   * @return {[type]} [description]
   */
  getScrollTop: function () {
    var that = this;
    if (wx.canIUse('getSystemInfo.success.screenWidth')) {
      wx: wx.getSystemInfo({
        success: function (res) {
          rate = res.screenWidth / 750;
          floatTop = 104 * rate;
          that.setData({
            scrollTop: 104 * res.screenWidth / 750,
            scrollHeight: res.screenHeight / (res.screenWidth / 750) - 128,
          });
        }
      });
    }
  },

  /**
    * 生命周期函数--监听页面加载
    */
  onPageScroll: function (event) {
    var scrollTop = event.scrollTop;
    if (scrollTop >= floatTop && !this.data.isShowFloatTab) {
      this.setData({
        isShowFloatTab: true,
      });
    } else if (scrollTop < floatTop && this.data.isShowFloatTab) {
      this.setData({
        isShowFloatTab: false,
      });
    }
  }

})
